package org.glorylight.hacks.social.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.glorylight.hacks.social.data.MessageData;
import org.glorylight.hacks.social.model.Message;
import org.glorylight.hacks.social.util.ModelHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class MessageService extends BaseService {
	private static final Logger log = LoggerFactory.getLogger(MessageService.class);

	@Transactional(readOnly = false)
	public void addMessage(MessageData data) throws Exception{
		if (log.isDebugEnabled())
			log.debug("adding new message for: {}", data.getSubject());
		add(ModelHelper.convertMessageData(data));
	}
	
	@Transactional(readOnly = false)
	public void deleteMessage(MessageData data) throws Exception {
		if (log.isDebugEnabled())
			log.debug("delete Message for: {}", data.getId());
		Message msg = findMessage(data.getId());
		delete(msg);
	}

	private Message findMessage(UUID id) {
		if (log.isDebugEnabled())
			log.debug("retrieve Message: {}", id);
		return em.find(Message.class, id);
	}
	
	public MessageData find(UUID id) {
		if (log.isDebugEnabled())
			log.debug("retrieve Message: {}", id);
		Message msg = em.find(Message.class, id);
		if (msg != null)
			return ModelHelper.convertMessage(msg);
		else
			return null;
	}

	public List<MessageData> findAllByUser(String userId) {
		if (log.isDebugEnabled())
			log.debug("find all message");
		List<Message> result = em.createNamedQuery("message-by-user", Message.class)
				.setParameter("userId", userId).getResultList();
		List<MessageData> datas = null;
		if (result.size() > 0){
			datas = new ArrayList<MessageData>();
			for (Message u : result)
				datas.add(ModelHelper.convertMessage(u));
		}
		
		return datas;
	}
	
	public Map<String, List<MessageData>> findAllByUserPerThread(String userId) {
		if (log.isDebugEnabled())
			log.debug("find all message");
		Map<String, List<MessageData>> map = new HashMap<String, List<MessageData>>();
		List<MessageData> result = findAllByUser(userId);
		List<MessageData> list = null;
		
		for (MessageData md : result) {
			if (map.containsKey(md.getSubject()))
				map.get(md.getSubject()).add(md);
			else {
				list = new ArrayList<MessageData>();
				list.add(md);
				map.put(md.getSubject(), list);
			}
		}
		
		return map;
	}
}
